package com.ai_daily.aitiantian.util;

import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.IBinder;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import androidx.core.app.NotificationCompat;
import androidx.core.content.FileProvider;


import com.ai_daily.aitiantian.Constants;
import com.ai_daily.aitiantian.R;
import com.ai_daily.aitiantian.api.ApiClient;
import com.ai_daily.aitiantian.api.IDownloadListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.io.File;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * @version 1.0 升级服务，负责后台下载，进度更新
 */

public class UpgradeService extends Service {
    private static final int DOWNLOAD_NOTIFICATION_ID = 100;
    private Call<ResponseBody> downBody;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        EventBus.getDefault().register(this);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent == null) {
            return START_NOT_STICKY;
        }
        downloadApkFile(this, intent.getStringExtra("url"), intent.getStringExtra("versionCode"));
        return START_STICKY;
    }

    private NotificationManager notificationManager;
    private NotificationCompat.Builder notificationBuilder;

    public void downloadApkFile(final Context context, String url, String versionCode) {
        if (TextUtils.isEmpty(url)) {
            return;
        }
        //记录下载链接和versionCode
//        new AppCacheManager().setDownloadUrl(url + "|" + versionCode);
        String rootDir = FileUtils.getRootDir(context), apkName = Constants.APK_NAME + versionCode + ".apk";
        createNotification(context, rootDir);
        final long startsPoint = getFileStart(rootDir, apkName);
        downBody = new ApiClient().downloadService(startsPoint, new IDownloadListener() {
            @Override
            public void onStartDownload(long length) {
                if (startsPoint < length * 0.8) { //未下载完
                    ThreadUtil.runOnMainThread(() -> AppUtils.showToast(context, context.getString(R.string.apk_download_tips)));
                }
            }

            @Override
            public void onProgress(float progress) {
                LogUtil.d(" download...... progress = " + (progress));
                if (progress < 1) {
                    updateNotification((int) (progress * 100));
                } else {
                    showDownloadResultNotification("下载成功");
                }
            }

            @Override
            public void onFail(@Nullable String errorInfo) {
                showDownloadResultNotification("下载失败");
                cancelNotificationLater();
                EventBus.getDefault().post(new MessageEvent(MessageEvent.DOWNLOADSUCCESS_FAIL));
            }
        }).download(url);
        assert downBody != null;
        downBody.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(@NotNull Call<ResponseBody> call, @NotNull Response<ResponseBody> response) {
                showDownloadResultNotification("下载成功");
                cancelNotificationLater();
//                Toast.makeText(context,"开始保存",Toast.LENGTH_LONG).show();
                ThreadUtil.runOnSubThread(() -> {
                    Log.d("DOWNLOAD",response.toString());
                    File file = FileUtils.saveFile(response, new File(rootDir, apkName), startsPoint);
//                    Toast.makeText(context,"保存成功",Toast.LENGTH_LONG).show();
//                    new AppCacheManager().clearDownloadInfo();
                    ThreadUtil.runOnMainThread(() -> {
                        // 兼容多版本,通过工具类安装
//                        Toast.makeText(context,"开始安装",Toast.LENGTH_LONG).show();
                        InstallUtil.getInstance().install(file.getAbsolutePath());
                    });
                });

                stopSelf();
            }

            @Override
            public void onFailure(@NotNull Call<ResponseBody> call, @NotNull Throwable t) {
            }
        });
    }


    @SuppressWarnings("deprecation")
    private void createNotification(Context context, String filedir) {
        notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel chan1 = new NotificationChannel("default", "Primary Channel", NotificationManager.IMPORTANCE_LOW);
            notificationManager.createNotificationChannel(chan1);
            notificationBuilder = new NotificationCompat.Builder(context, "default");
        } else {
            notificationBuilder = new NotificationCompat.Builder(context);
        }
        Intent installIntent = new Intent();
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
            installIntent.setDataAndType(Uri.parse("file://" + filedir), "application/vnd.android.package-archive");
            installIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        } else {
            Uri apkUri = FileProvider.getUriForFile(context, Constants.GLOBAL_PROVIDER_PATH, new File(filedir));
            Intent install = new Intent(Intent.ACTION_VIEW);
            //由于没有在Activity环境下启动Activity,设置下面的标签
            install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            //添加这一句表示对目标应用临时授权该Uri所代表的文件
            install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            install.setDataAndType(apkUri, "application/vnd.android.package-archive");
        }
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, installIntent, 0);
        notificationBuilder.setContentIntent(pendingIntent);
    }

    private long getFileStart(String filedir, String filename) {
        long length = new File(filedir, filename).length();
        return length > 0 ? length - 1 : length;
    }

    private void updateNotification(int current) {
        notificationBuilder.setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle("正在下载")
                .setContentText(current + "%")
                .setProgress(100, current, false);
        notificationManager.notify(DOWNLOAD_NOTIFICATION_ID, notificationBuilder.build());
    }

    private void showDownloadResultNotification(String contentTitle) {
        notificationBuilder.setSmallIcon(R.mipmap.ic_launcher)
                .setTicker(contentTitle)
                .setContentTitle(contentTitle)
                .setAutoCancel(true);
        notificationManager.notify(DOWNLOAD_NOTIFICATION_ID, notificationBuilder.build());
    }

    private void cancelNotificationLater() {
        new WeakHandler(Looper.getMainLooper()).postDelayed(() ->
                notificationManager.cancel(DOWNLOAD_NOTIFICATION_ID), 500L);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {
        if (event.type == MessageEvent.SYSTEM_EXIT) {
            stopSelf();
            if (downBody != null) {
                downBody.cancel();
            }
            if (notificationManager != null) {
                cancelNotificationLater();
            }
        }
    }
}
